package com.dsk.connector.commons.utils;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 序列化和反序列化工具类
 */
public class SerializeUtils {
    /**
     * 序列化对象为字符串
     * @param object
     * @return
     */
    public static String hessianSerialize(Object object) {
        Hessian2Output oo = null;
        String result = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oo = new Hessian2Output(bos);
            oo.writeObject(object);
            oo.flush();
            byte[] resultByte = bos.toByteArray();
            return new String(resultByte, "ISO-8859-1");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 反序列化字符串为对象
     * @param msg
     * @return
     * @param <T>
     */
    public static<T> T hessianSerializeToObject(String msg) {
        if(StringUtils.isBlank(msg)){
            return null;
        }
        try {
            ByteArrayInputStream is = new ByteArrayInputStream(msg.getBytes("ISO-8859-1"));
            Hessian2Input input = new Hessian2Input(is);
            Object result = input.readObject();
            return (T)result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
